/*
 * Copyright (C) 2021 Kaihongdigi Limited, 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

#include "image_utils.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#include <utility>
unsigned char *ImageUtils::Imread(const std::string& path, int& h, int& w, int& c){
    unsigned char* pixeldata = stbi_load(path.c_str(), &w, &h, &c, 3);
    if (c == 3)
    {
        unsigned char* p = pixeldata; 
        for (int i = 0; i < w * h; i++)
        {
            std::swap(pixeldata[0], pixeldata[2]);
            p += 3;
        }
    }
    return pixeldata;

}


void ImageUtils::Imwrite(const std::string& path,  unsigned char* data, int h, int w, int c){
   
    unsigned char *p = data;	
    for (int i = 0; i < w *h; i++)
    {
        std::swap(data[0], data[2]);
        p += 3;
    }
    int quality = 95;
    stbi_write_jpg(path.c_str(), w, h, c, data, quality);
}

/*
void ImageUtils::Rectangle(const unsigned char*data, int w, int h, int c, int x1, int y1, int x2, int y2){

    int x = std::min(x1, x2);
    int y = std::min(y1, y2);
    int width = std::max(x1, x2) - x;
    int height = std::max(y1, y2) - y;

    unsigned int color = 0;
    unsigned char* border_color = (unsigned char*)&color;

    border_color[0] = 0;
    border_color[1] = 255;
    border_color[2] = 0;
    ncnn::draw_rectangle_c3(data, w, h, x, y, width, height, color, 1);

}
*/

void ImageUtils::FreeImage(unsigned char*data) {
    stbi_image_free(data);
}
